<template>
  <div style="padding:15px;padding-bottom: 300px;">
    <h2 style="text-align: left;">刘大爷的代码自动生成</h2>
    <el-form ref="formRef" :model="state.topInfo" :rules="rules" :label-width="100">
      <el-row>
        <el-col :span="6">
          <el-form-item label="关键字" prop="name">
            <el-input placeholder="一般填写文件名称" v-model="state.topInfo.name" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="路径" prop="path">
            <el-input placeholder="例：exam/newexam" v-model="state.topInfo.path" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="菜单路径" prop="menuPath">
            <el-input v-model="state.topInfo.menuPath" placeholder="安全教育考试-我的考试" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="历史记录">
            <el-select @change="historyChange" clearable v-model="state.topInfo.history" placeholder="请选择">
              <el-option :key="index" v-for="( item, index ) in  state.historySelectList " :label="item.name"
                :value="item.name" />
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
    <div class="button_wrap" style="padding-bottom: 15px;">
      <el-button @click="handleAdd" type="primary">新增</el-button>
    </div>
    <el-row class="border" style="width: 100%;">
      <el-col :span="24">
        <div style="text-align: left;display: flex; width: 20%;">
          <el-checkbox v-model="state.isMultiseriate" label="一行多列" value="1" size="large" />
          <el-input v-if="state.isMultiseriate == '1'" style="margin-left: 10px;margin-right: 10px;"
            v-model="state.multiseriateValue"></el-input>
          <el-checkbox v-model="state.isExport" label="列表导出" value="1" size="large" />
        </div>
      </el-col>
    </el-row>
    <el-row class="border">
      <el-col :span="4">
        <h4>名称</h4>
      </el-col>
      <el-col :span="4">
        <h4>字段名称</h4>
      </el-col>
      <el-col :span="3">
        <h4>字段类型</h4>
      </el-col>
      <el-col :span="3">
        <h4>具体实现</h4>
      </el-col>
      <el-col :span="5">
        <h4>操作类型</h4>
      </el-col>
      <el-col :span="3">
        <h4>是否自定义</h4>
      </el-col>
      <el-col :span="2">
        <h4>操作</h4>
      </el-col>
    </el-row>

    <draggable item-key="id" @change="moveChange" v-model="state.tablePropsList" group="people" @start="state.drag = true"
      @end="state.drag = false">
      <template #item="{ element, index }">
        <el-row class="border">
          <el-col :span="4">
            <div class="name">
              <el-input v-model="element.name" />
            </div>
          </el-col>
          <el-col :span="4">
            <div class="field">
              <el-input @focus.stop v-model="element.field" />
            </div>
          </el-col>
          <el-col :span="3">
            <div class="type">
              <el-select @change="setSubtypeOptions(element, index)" v-model="element.type" placeholder="请选择类型"
                style="width: 240px">
                <el-option v-for=" item  in  state.typeOptions " :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </div>
          </el-col>
          <el-col :span="3">
            <div class="subType">
              <el-select v-if="![...state.subShowTextareaList, ...state.subShowMaxlengthList].includes(element.type)"
                :disabled="!element.type || element.subtypeOptions.length <= 0" v-model="element.subType"
                placeholder="请选择具体类型" style="width: 240px">
                <el-option v-for=" item  in  element.subtypeOptions " :key="item.key" :label="item.key"
                  :value="item.key" />
              </el-select>
              <el-input v-if="state.subShowTextareaList.includes(element.type)" placeholder="1:'是'
0:'否'" v-model="element.formatterContent" type="textarea"></el-input>
              <div v-if="state.subShowMaxlengthList.includes(element.type)" style="display: flex;align-items: center;"
                class="flex justify_content_center">
                <span style="font-size: 13px;">字数：</span><el-input style="flex: 1;" type="number"
                  v-model="element.formatterContent"></el-input>
              </div>

            </div>
          </el-col>
          <el-col :span="5">
            <div class="handleType">
              <el-checkbox-group v-model="element.handleTypeCheckList">
                <el-checkbox label="search" value="search" />
                <el-checkbox label="table" value="table" />
                <el-checkbox label="form" value="form" />
                <el-checkbox v-if="element.handleTypeCheckList.includes('form')" label="required" value="required" />
              </el-checkbox-group>
            </div>
          </el-col>
          <el-col :span="3">
            <el-radio-group v-model="element.formatter">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
            <!-- <el-input v-if="element.formatter == '1'" v-model="element.formatterContent" type="textarea"></el-input> -->
          </el-col>
          <el-col :span="2" style="display: flex;justify-content: center;">
            <el-link @click="handleDelete(index)" type="danger">删除</el-link>
          </el-col>
        </el-row>
      </template>
    </draggable>
    <el-row>
      <el-col :span="24">
        <div class="button_wrap">
          <el-button @click="createCode(1)" type="primary">生成v3代码</el-button>
          <el-button @click="createCode(2)" type="primary">生成v2代码</el-button>
        </div>
      </el-col>
    </el-row>
    <div style="padding: 20px 0;" v-if="state.activeType == '1'">
      <el-tabs type="border-card">
        <el-tab-pane label="列表">
          <el-input :rows="60" v-model="state.v3TableCode" type="textarea"></el-input>
        </el-tab-pane>
        <el-tab-pane label="弹窗">
          <el-input :rows="60" v-model="state.v3DialogCode" type="textarea"></el-input>
        </el-tab-pane>
        <el-tab-pane label="rules">
          <el-input :rows="60" v-model="state.v3RulesCode" type="textarea"></el-input>
        </el-tab-pane>
        <el-tab-pane label="类型定义">
          <el-input :rows="60" v-model="state.v3typedefCode" type="textarea"></el-input>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div style="padding: 20px 0;" v-if="state.activeType == '2'">
      <el-tabs type="border-card">
        <el-tab-pane label="列表jsp">
          <el-input :rows="60" v-model="state.v2TableCode" type="textarea"></el-input>
        </el-tab-pane>
        <el-tab-pane label="列表js">
          <el-input :rows="60" v-model="state.v2TablejsCode" type="textarea"></el-input>
        </el-tab-pane>
        <el-tab-pane label="弹窗">
          <el-input :rows="60" v-model="state.v2DialogCode" type="textarea"></el-input>
        </el-tab-pane>
        <el-tab-pane label="弹窗js">
          <el-input :rows="60" v-model="state.v2DialogjsCode" type="textarea"></el-input>
        </el-tab-pane>
        <el-tab-pane label="Api">
          <el-input :rows="60" v-model="state.v2ApijsCode" type="textarea"></el-input>
        </el-tab-pane>
      </el-tabs>
    </div>
    <Tool ref="toolRef"></Tool>
  </div>
</template>
<script setup>
import { reactive, onMounted, ref } from 'vue';
import draggable from 'vuedraggable';
import { pinyin } from 'pinyin-pro';
import { configRules } from './config/rule.config.ts';
import { humpTo } from '@/utils/index.ts';

import Tool from './tools/toolsIndex.vue'
const rules = reactive(configRules);
const formRef = ref();
// const toolRef = ref()
const state = reactive({
  drag: false,
  activeType: 1,//1：v3代码、2：v2代码
  v3TableCode: "",//v3列表代码
  v3DialogCode: "",//v3弹窗代码
  v3RulesCode: "",//v3弹窗表单规则rules
  v3typedefCode: "",//v3类型定义
  v2TableCode: "",//v2列表jsp
  v2TablejsCode: "",//列表js
  v2DialogCode: "",//弹窗
  v2DialogjsCode: "",//弹窗js
  v2ApijsCode: "",//api
  conInfo: "",
  isMultiseriate: false,//是否开启一行多列
  isExport: false,//列表是否需要导出
  multiseriateValue: 2,
  handleTypeCheckList: [],//操作类型
  selectRows: [],
  historySelectList: [],
  historySesstion: {},
  typeOptions: [
    { id: 1, name: "input" },
    { id: 2, name: "select" },
    { id: 3, name: "textarea" },
    { id: 4, name: "日期" },
    { id: 5, name: "部门" },
    { id: 6, name: "人员选择框" },
    { id: 7, name: "上传文件" },
    { id: 8, name: "上传图片" },
    { id: 9, name: "单选" },
    { id: 10, name: "多选" },
  ],
  subShowTextareaList: [2, 9, 10],
  subShowMaxlengthList: [1, 3],
  tablePropsList: [
    {
      "name": "测试一",
      "field": "ceshiyi",
      "type": 1,
      "subType": "",
      "formatter": "0",
      "subtypeOptions": [],
      "handleTypeCheckList": [
        "search",
        "table",
        "form"
      ],
      "formatterContent": ""
    },
    {
      "name": "测试二",
      "field": "ceshier",
      "type": 2,
      "subType": "",
      "formatter": "0",
      "subtypeOptions": [],
      "handleTypeCheckList": [
        "form",
        "required"
      ],
      "formatterContent": "1:'是'\n2:'否'"
    },
    {
      "name": "测试三",
      "field": "ceshisan",
      "type": 4,
      "subType": "daterange",
      "formatter": "0",
      "subtypeOptions": [
        {
          "key": "year"
        },
        {
          "key": "date"
        },
        {
          "key": "datetime"
        },
        {
          "key": "daterange"
        },
        {
          "key": "datetimerange"
        }
      ],
      "handleTypeCheckList": [
        "search",
        "table",
        "form",
        "required"
      ],
      "formatterContent": ""
    },
    {
      "name": "测试四",
      "field": "ceshisi",
      "type": 5,
      "subType": "单选",
      "formatter": "0",
      "subtypeOptions": [
        {
          "key": "单选"
        },
        {
          "key": "多选"
        }
      ],
      "handleTypeCheckList": [
        "search",
        "form"
      ],
      "formatterContent": ""
    },
    {
      "name": "测试五",
      "field": "ceshiwu",
      "type": "",
      "subType": "",
      "formatter": "0",
      "subtypeOptions": [],
      "handleTypeCheckList": [],
      "formatterContent": ""
    }
  ],
  topInfo: {
    name: "testCode",//关键字名称
    menuPath: "",//菜单路径名称
    path: "",//文件引入路径
    history: "",
  }
})
onMounted(() => {
  // 获取历史列表
  getHistoryList();
});
// 新增
const handleAdd = () => {
  state.tablePropsList.push({ name: "", field: "", type: "", subType: "", formatter: "0", subtypeOptions: [], handleTypeCheckList: [], formatterContent: "" })
}
// 删除
const handleDelete = (index) => {
  state.tablePropsList.splice(index, 1)
}
// 确定主类型后生成具体实现类型
const setSubtypeOptions = (element) => {
  const { type } = element;
  element.formatterContent = ""
  switch (type) {
    case 1://input
      element.formatterContent = 100;
      break;
    case 3://textarea
      element.formatterContent = 1000;
      break;
    case 4://日期
      element.subtypeOptions = [
        { key: "year" },
        { key: "date" },
        { key: "datetime" },
        { key: "daterange" },
        { key: "datetimerange" }];
      break;
    case 5://部门
      element.subtypeOptions = [
        { key: "单选" },
        { key: "多选" }];
      break;
    case 6://部门
      element.subtypeOptions = [
        { key: "单选" },
        { key: "多选" }];
      break;
  }
}
// 生成代码
const createCode = (type) => {

  formRef.value.validate((valid, fields) => {
    if (valid) {
      state.tablePropsList = setFieldName();//自动生成字段

      // 当前数据存储到本地
      setlocalStorage();
      state.activeType = type
      if (state.activeType == '1') {
        createv3SearchHeaderCode();//生成头部搜索代码
        createv3TableCode();// v3列表生成
        createv3ComponentsCode();// v3组件生成
        createv3TableJSCode();// v3tablejs生成
        createv3DialogCode();//v3Dialog生成
        createv3DialogJsCode();//v3Dialog  js生成
        createv3RulesCode();//v3弹窗表单规则rules
        createv3typedefCode();//v3类型定义
      }
      // 生成v2代码
      if (state.activeType == '2') {
        createv2topCode();//获取头部引入代码
        createv2SearchHeaderCode();//生成v2头部搜索代码
        createv2TableCode();// v2列表生成
        createv2TalejsDataCode();//v2列表js生成data
        createv2TalejsCreated();// 获取v2列表created
        createv2TalejsMethods();// 获取v2列表js methods
        createv2DialogtopCode();//获取v2弹窗头部引入代码
        createv2DialogHtmlCode();//获取v2弹窗html
        createv2DialogJsCode();//获取v2弹窗js
        createV2ApiCode();// 生成v2api代码
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 根据类型获取数据
const getTypeList = (type) => {
  const params = type.split(",");
  return state.tablePropsList.filter(i => params.every(item => i.handleTypeCheckList.includes(item)))
}
// 根据form类型判断是否存在数据
// const formHasType = (types) => {
//   const typeList = types.split(',');
//   return state.tablePropsList.filter(item => typeList.includes(item.type))
// }
// 获取有名字的数据生成字段名称
const setFieldName = () => {
  const tablePropsList = state.tablePropsList.flatMap(row => {

    const { name, field } = row;
    if (name) {
      if (!field) {
        row.field = _turnToPinyin(name)
      }
      return row;
    } else {
      return []
    }

  })
  console.log(tablePropsList)
  return tablePropsList;
}
/**
 * v3生成代码开始----------------
 */
// 获取搜索项html
const createv3SearchHeaderCode = () => {
  state.v3TableCode = `<template>
    <div class="page_main">\n`
  const list = getTypeList("search");
  state.v3TableCode += `\t<cSearch ${list.length > 3 ? 'showMore' : ''} @search="search" :formModel="state.queryParams">\n\t\t<el-row>\n`
  list.forEach(item => {
    const { name, field, type } = item;
    let singleItem = `\t\t\t<el-col :span="8">\n<el-form-item label="${name}" prop="${field}">`
    singleItem += getV3FormItemHtml(type, "queryParams", item);
    singleItem += `</el-form-item>\n</el-col>`
    state.v3TableCode += singleItem;
  })
  state.v3TableCode += `</el-row>\n</cSearch>\n`;
}
const getV3FormItemHtml = (type, subobjName, element) => {
  const { field, subType, formatterContent = 100 } = element;
  const selectname = `${field}SelectList`;
  const maxlength = formatterContent ? `maxlength=${formatterContent}` : ""
  switch (type) {
    case 1:
      return `<el-input ${maxlength} v-model="state.${subobjName}.${field}" placeholder="请输入"></el-input>`
    case 2:
      return `<el-select clearable v-model="state.${subobjName}.${field}" placeholder="请选择">
              <el-option v-for="item in state.${selectname}" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>`
    case 3:
      return `<el-input rows="3" type="textarea" ${maxlength} v-model="state.${subobjName}.${field}" placeholder="请输入"></el-input>`
    case 4:
      return getDateHtml(subobjName, element, 1)
    case 5:
      if (subType == "单选") {
        return `<singleTreeSelect :checkedList="state.checkedOrgList" v-model="state.${subobjName}.${field}">
              </singleTreeSelect>`
      } else {
        return `<multiTreeSelect :checkedList="state.checkedOrgList" v-model="state.${subobjName}.${field}">
              </multiTreeSelect>`
      }
    case 6:
      return `<personSelect ${subType == "单选" ? "single" : ""} :checkedList="checkPersonList" @select="selectPerson" type="1"></personSelect>`
    case 7:
      return `<uploadFile @remove="removeFile" :limit="1" text="选择文件" exts="xlsx,xls" @success="uploadSuccess"
              v-model:fileList="state.fileList">
            </uploadFile>`
    case 8:
      return `<uploadImgs @remove="removeimg" @success="uploadSuccessimg" v-model:fileList="fileListimg1">
          </uploadImgs>`

    case 9:
      return getRadioHtml(subobjName, element, 1)
    case 10:
      return getCheckBoxHtml(subobjName, element, 1)
  }
}
// v3列表生成
const createv3TableCode = () => {
  const list = getTypeList("table");
  const { name } = state.topInfo;
  state.v3TableCode += `<sTable ref="${name}ListTableRef" :query-params="state.queryParams" :request-api="getTableList"
      :table-header="tableHeader">
      <template #toolbar>
        <el-button v-hasPerm="'${_getCodeName()}'" @click="handleAdd" type="primary">新增</el-button>
      </template>
   `
  list.forEach(item => {
    const { name, field, formatter } = item;
    if (formatter == '1') {
      state.v3TableCode += `<!-- ${name} -->
      <template #status="scope">
        <p class="ellipsis_1" :title="scope.row.${field}" v-if="scope.row.${field}" style="text-align: center;">
          {{scope.row.${field}}}
        </p>
        <p v-else>-</p>
      </template>`;
    }
  })
  state.v3TableCode += `</sTable>\n`;
}
// v3组件生成
const createv3ComponentsCode = () => {
  state.v3TableCode += `<editDialog :pageType="state.pageType" @submit="search" :rowId="state.activeId" ref="editRef">
    </editDialog>\n</div>\n</template>`
}
// v3tablejs生成
const createv3TableJSCode = () => {
  const { name } = state.topInfo;
  state.v3TableCode += `<script setup lang="ts" name="${_getFirstUpperCase(name)}">
${getv3TableJSImportCode()}
${getv3TableJSStateCode()}
${getv3TableJSHandleCode()}
${getv3TableJStableHeaderCode()}
${getv3TableJSFormatQueryParams()}
${getv3TableJSOthers()}
`
}
const getv3TableJSImportCode = () => {
  const { name } = state.topInfo;
  let html = `import {reactive, ref } from 'vue';
import editDialog from './handle/edit.vue';
import { get${_getFirstUpperCase(name)}, delete${_getFirstUpperCase(name)} } from '@/api/${name}';
import { TableHeaderProps } from '@/components/Table/interface/index'; //获取tableHeader定义属性
import { TableStateData } from './interface/index';
import message from '@/utils/message';`
  html += `import { useExport } from "@/hooks/useExport";`
  return html;
}
const getv3TableJSStateCode = () => {
  const list = getTypeList("search");
  const { name } = state.topInfo;
  let html = `const state = reactive<TableStateData>({
  isView: false,
  activeId: "", //当前操作数据id`
  list.forEach(item => {
    const { name, field, type, formatterContent } = item;
    if (type == "2") {//select
      html += `${field}SelectList:[//${name}下拉数据\n`
      const options = areaOptions(formatterContent)
      options.forEach(option => {
        html += `{id:${option.id},name:${option.name}},\n`
      })
      html += `],\n`
    }
    //部门选择,人员选择框,上传文件,上传图片
    if (type == "5" || type == "6" || type == "7" || type == "8") {
      html += `${field}List:[],//${name}回显数据\n`
    }
    if (type == "5") {
      html += `initialOrgList:[],//${name}回显部门\n`
    }
  });
  html += `queryParams: {
    pageNum: 1,
    pageSize: 10,`;
  list.forEach(item => {
    const { name, field } = item;
    html += `${field}: undefined,//${name}\n`;
  });
  html += `
  },
});
const editRef = ref(); //编辑组件的ref
const ${name}ListTableRef = ref();\n`
  return html;
}
const getv3TableJSHandleCode = () => {
  const { name } = state.topInfo;
  let html = `// 新增
const handleAdd = () => {
  state.activeId = "";
  state.isView = false;
  editRef.value.openDialog();
};
// 查看
const handleView = (row: any) => {
  state.activeId = row.id;
  state.isView = true;
  editRef.value.openDialog();
};
// 编辑
const handleEdit = (row: any) => {
  state.activeId = row.id;
  state.isView = false;
  editRef.value.openDialog();
};
// 删除
const handleDel = (row: any) => {
  const data = {
    id: row.id
  }
  message
    .confirm()
    .then(action => {
      delete${_getFirstUpperCase(name)}(data).then((res: any) => {
        message.success(res.msg || res.data?.msg || '操作成功');
        search();
      });
    })
    .catch((err: any) => {
      console.log('取消删除');
    });
};`
  return html;
}
const getv3TableJStableHeaderCode = () => {
  const list = getTypeList("table");
  let html = `const tableHeader: TableHeaderProps[] = [
    { prop: "index", label: "序号" },\n`;
  list.forEach(item => {
    const { name, field, formatter } = item;
    if (formatter == '1') {
      html += `{prop: "${field}", label: "${name}", cellset: true},\n`;
    } else {
      html += `{prop: "${field}", label: "${name}"},\n`;
    }
  });
  html += `{
    prop: 'oper',
    label: '操作',
    width: 150,
    cellset: true,
    oper: [
      { name: '查看', onClick: handleView, permission: '${_getCodeName('view')}' },
      { name: '编辑', onClick: handleEdit, permission: '${_getCodeName('edit')}' },
      {
        name: '删除',
        type: 'danger',
        permission: '${_getCodeName('delete')}',
        onClick: handleDel
      }
    ]
  }
];`
  return html;
}
//获取v3列表js  formatQueryParams
const getv3TableJSFormatQueryParams = () => {
  let html = `//获取搜索数据
    const formatQueryParams = (params: any) => {
       //获取搜索项
       const newParams = JSON.parse(JSON.stringify(params));`
  const list = getTypeList("search");
  list.forEach(item => {
    const { type, subType, field, name } = item;
    if (type == '4') {//日期选择
      if (subType == "daterange") {
        html += `//${name}
            if (newParams.${field} && newParams.${field}.length > 0 && newParams.${field}[0]) {
                newParams.starttime = newParams.${field}[0] + " 00:00:00";
                newParams.endtime = newParams.${field}[1] + " 23:59:59";
            } else {
                newParams.starttime = undefined;
                newParams.endtime = undefined;
            }
            delete newParams.${field};`
      }
    }
  })
  html += `return newParams;
  },\n`
  return html;
}
//获取v3列表js 其他函数
const getv3TableJSOthers = () => {
  const { name } = state.topInfo;
  let html = `// 搜索
const search = async () => {
  // 重新加载table表格
  ${name}ListTableRef.value.search();
};
const getTableList = (params: any) => {
  // 这里可以做一些搜索项的处理，比如想加载全部数据，可以给params.pageSize设置一个很大的值
  const newQueryParams = formatQueryParams(params);
  return get${_getFirstUpperCase(name)}List(newQueryParams);
};`
  return html;
}
// v3Dialogjs生成
const createv3DialogCode = () => {
  state.v3DialogCode += `<template>
  <div class="">
    <cDialog :title="state.title" @close="dialogClose()" size="middle" v-model:visible="state.visible">
      <el-form v-if="!state.isView" ref="ruleFormRef" :model="state.form" :rules="rules" label-width="120px"
        size="default" status-icon>
        ${getV3DialogFormItem()}
        </el-form>
        <el-form v-else ref="ruleFormRef" :model="state.form" label-width="120px" class="demo-ruleForm" size="default" status-icon>
        ${getV3DialogViewFormItem()}
        </el-form>
      <template #footer>
        <submit-button v-if="!state.isView" :formref="ruleFormRef" :api="api" @response="response">确定</submit-button>
        <el-button :type="state.isView ? 'primary' : ''" @click="dialogClose()">{{ state.isView ? '关闭' : '取消'
        }}</el-button>
      </template>
    </cDialog>
  </div>
</template>\n`;
}
const getV3DialogFormItem = () => {
  const list = getTypeList("form");
  let html = "";
  let colCount = 1;
  list.forEach((item, index) => {
    const { name, field, type } = item,
      { isMultiseriate, multiseriateValue } = state,
      colnum = 24 / multiseriateValue;
    let singleItem = '';
    // 开启多行且一行大于1个表单
    if (isMultiseriate && multiseriateValue > 1) {
      if (colCount === 1) {
        singleItem += `<el-row>\n`
      }
      singleItem += `<el-col :span="${colnum}">\n`
    }
    singleItem += `<el-form-item label="${name}" prop="${field}">\n`
    singleItem += getV3FormItemHtml(type, "form", item);
    singleItem += `\n</el-form-item>\n`
    if (isMultiseriate && multiseriateValue > 1) {
      singleItem += `</el-col>\n`;
      if (colCount >= multiseriateValue || index == list.length - 1) {
        colCount = 1;
        singleItem += `</el-row>\n`
      } else {
        colCount++;
      }
    }
    html += singleItem;
  })
  return html;
}
const getV3DialogViewFormItem = () => {
  const list = getTypeList("form");

  // 查看页面
  let html = ``
  let colCount = 1;
  list.forEach((item, index) => {
    const { name, field, type } = item,
      { isMultiseriate, multiseriateValue } = state,
      colnum = 24 / multiseriateValue;
    // 开启多行且一行大于1个表单
    if (isMultiseriate && multiseriateValue > 1) {
      if (colCount === 1) {
        html += `<el-row>\n`
      }
      html += `<el-col :span="${colnum}">\n`
    }
    if (type == '5' || type == '6') {
      html += `<el-form-item label="${name}：">
        <p class="view_text">{{getValid(form.${field}Name)}}</p>
    </el-form-item>\n`
    } else if (type == '7') {
      html += `<el-form-item label="${name}：" prop="${field}">
        <uploader
              isView
              :file-list="${field}List">
        </uploader>
      </el-form-item>\n`;
    } else if (type == '8') {
      html += `<el-form-item label="${name}：" prop="${field}">
        <uploader
              isView
              file-type="image"
              :file-list="${field}List">
        </uploader>
      </el-form-item>\n`;
    } else {
      html += `<el-form-item label="${name}：" prop="${field}">
        <p class="view_text">{{getValid(form.${field})}}</p>
    </el-form-item>\n`;
    }
    if (isMultiseriate && multiseriateValue > 1) {
      html += `</el-col>\n`;
      if (colCount >= multiseriateValue || index == list.length - 1) {
        colCount = 1;
        html += `</el-row>\n`
      } else {
        colCount++;
      }
    }
  })

  return html;
}
// 生成v3
const createv3DialogJsCode = () => {
  const { name } = state.topInfo;
  state.v3DialogCode = `<script setup lang="ts">
  import { reactive, ref, nextTick } from 'vue';
import type { FormRules, UploadProps } from 'element-plus';
import message from '@/utils/message';
import { assign } from '@/utils/index';
import { get${_getFirstUpperCase(name)}Info, add${_getFirstUpperCase(name)}, edit${_getFirstUpperCase(name)} } from '@/api/${name}';
import { EditStateData } from '../interface/index';
import { configRules } from '../config/rule.config';

const ruleFormRef = ref();
const rules = reactive<FormRules>(configRules);
// 定义父级发出的事件
const emit = defineEmits(['submit']);
const props = defineProps({
  /**
   * 根据id获取数据
   */
  rowId: {
    type: [Number, String],
    default: ''
  },
  isView: {
    type: Boolean,
    default: false
  },
});
${getV3DialogStateCode()}
${getV3DialogDetailCode()}
${getv3DialogjsFormatViewForm()}
${getV3DialogResetCode()}
${getv3DialogjsApiResponse()}
${getv3DialogOther()}
${getv3DialogOpenClose()}
defineExpose({
  openDialog
});
<\/script>
<style scoped>

</style>`
}
// 获取v3弹窗自定义变量state
const getV3DialogStateCode = () => {
  const list = getTypeList("form");
  let html = `const state = reactive<EditStateData>({
             isView: false,
             visible: false,
             title: '新增',
            form: {
              id: undefined, //id\n`;
  list.forEach(item => {
    const { name, field } = item;
    html += `${field}:undefined,//${name}\n`;
  })
  html += ` },\n`;

  // 额外需要赋值的回显数据
  list.forEach(item => {
    const { name, field, type, formatterContent } = item;
    if (type == "2") {//select
      html += `${field}SelectList:[//${name}下拉数据\n`
      const options = areaOptions(formatterContent)
      options.forEach(option => {
        html += `{id:${option.id},name:${option.name}},\n`
      })
      html += `],\n`
    }
    //部门选择,人员选择框,上传文件,上传图片
    if (type == "5" || type == "6" || type == "7" || type == "8") {
      html += `${field}List:[],//${name}回显数据\n`
    }
    if (type == "5") {
      html += `initialOrgList:[],//${name}回显部门\n`
    }
  });
  html += `});\n`;
  return html;
}
// 获取v3弹窗初始变量
const getV3DialogResetCode = () => {
  const list = getTypeList("form");
  let html = `const resetRuleForm = () => {
     state.form = {
       id: '', //id`;
  list.forEach(item => {
    const { name, field } = item;
    html += `${field}:"",//${name}\n`;
  })
  html += ` },\n`;

  // 额外需要赋值的回显数据
  list.forEach(item => {
    const { name, field, type, } = item;
    //部门选择,人员选择框,上传文件,上传图片
    if (type == "5" || type == "6" || type == "7" || type == "8") {
      html += `state.${field}List = [];//${name}回显数据\n`
    }
  });
  html += `};\n`;
  return html;
}
// 获取v3弹窗获取详情
const getV3DialogDetailCode = () => {
  let html = `
  const getInfo = async (id: number | string) => {
     const params = {
      id,
    }
    const { data } = await getLawInv(id);
    formatViewForm(data || {});
};
//获取有效值
const getValid = (params: any) => {
  if (params || params == '0') {
    return params;
  }
  return "-"
}\n`;
  return html;
}
// 获取v3弹窗js methods formatViewForm
const getv3DialogjsFormatViewForm = () => {
  const list = getTypeList("form");
  let html = `const formatViewForm = (data: any) => {`;
  // 声明变量
  html += `\nconst {`;
  list.forEach(item => {
    const { field, type } = item;
    if (type == '6') {
      html += `${field}, ${field}Names, userModels,`
    }
    if (type == '5') {
      html += `${field}, ${field}Names,`
    }
    if (type == '7' || type == '8') {
      html += `fileModels`
    }
  })
  html += `} = data;`;
  html += `let newForm = JSON.parse(JSON.stringify(data));
            newForm = assign(state.form,newForm);`
  list.forEach(item => {
    const { name, field, type } = item;
    if (type == '6') {
      html += `//${name}选择
            //可能方法一
            if(${field} && ${field}Names){
                state.${field}List = [{id:${field},name:${field}Names}]
            }
            //可能方法二
            if(userModels?.length>0){
                state.${field}List = userModels.map(person=>{
                    const {${field},${field}Names} = person;
                    return {name:${field}Names,id:${field}}
                })
            }\n`;
    }
    if (type == '5') {
      html += `//部门选择
            newForm.${field} = String(${field});
            if(${field} && ${field}Names){
                this.${field}List = [{orgId:String(${field}),text:${field}Names}]
            }\n`;
    }
    if (type == '7' || type == '8') {
      const filename = ' `${ filetitle }.${ suffix } `';
      html += `//上传文件
            if(fileModels?.length>0){
                this.fileList = fileModels.map(item => {
                    let {filetitle, suffix, id} = item;
                    let obj = {
                        id,
                        name: ${filename}
                    }
                    return obj;
                })
            }
            return newForm;
        };\n`
    }
  })
  return html;
}
// 获取v3弹窗js api response formatSubmitForm
const getv3DialogjsApiResponse = () => {
  const { name } = state.topInfo;
  let html = `const formatSubmitForm = () => {
            const newData = JSON.parse(JSON.stringify(this.form));
            return newData;
        };
       const api = () => {
            const form = formatSubmitForm(this.form);
            if (state.form.id) {
                return ${humpTo(name)}_api.edit${_getFirstUpperCase(name)}(form);
            } else {
                return ${humpTo(name)}_api.add${_getFirstUpperCase(name)}(form);
            }
        },
        response(res) {
            const { data, success } = res;
            if (success) {
              message.success(res.msg || data?.msg || '操作成功');
              dialogClose();
            } else {
              message.error(res.msg || data?.msg || '操作失败');
            }
            emit('submit');
        },`;
  return html;
}
const getv3DialogOpenClose = () => {
  let html = `
  // 打开新增编辑弹窗
const openDialog = () => {
  state.visible = true;
  resetRuleForm();
  nextTick(() => {
    state.form.id = props.rowId;
    state.isView = props.isView;
    if (props.rowId) {
      // 编辑的情况获取数据
      getInfo(props.rowId);
      state.title = state.isView ? '查看' : '编辑';
    } else {
      state.title = '新增';
    }
  });
};
  // 关闭弹窗
const dialogClose = () => {
  state.visible = false;
};`
  return html
}
const getv3DialogOther = () => {
  const list = getTypeList("form");
  let html = '';
  if (list.find(item => item.type == '6')) {
    html += `personSelect(data) {
          state.form.userIds = data.map(person=>person.id).join(",");
          state.checkedList = data;
      },\n`;
  }
  if (list.find(item => (item.type == '7' || item.type == '8'))) {
    html += `const uploadSuccess: UploadProps['onSuccess'] = (file: any) => {
  state.form.files = state.fileList.joinMap("id")
};
const removeFile: UploadProps['onRemove'] = (file: any, uploadFiles: any) => {
  const id = file.id;
  state.fileList = state.fileList.filter(file => {
    return file.id != id
  });
  state.form.files = state.fileList.joinMap("id")\n `
  }
  return html;
}
// v3弹窗表单规则rules
const createv3RulesCode = () => {
  const list = getTypeList("form,required");
  if (list.length > 0) {
    state.v3RulesCode = `export const configRules = {\n`;
    list.forEach(item => {
      const { name, field, type } = item;
      const blurArr = ["1", "3"];
      if (blurArr.includes(type)) {
        state.v3RulesCode += `${field}:[
          {required: true, message: "请输入${name}", trigger: "blur"},
      ],\n`;
      } else {
        state.v3RulesCode += `${field}:[
          {required: true, message: "请选择${name}", trigger: "change"},
      ],\n`;
      }
    });
    state.v3RulesCode += `},\n`;
  }
}
// v3类型定义
const createv3typedefCode = () => {
  const list = getTypeList("search");
  const list1 = getTypeList("form");
  state.v3typedefCode = `import { ReqPage } from '@/api/common/types';
import { TableHeaderProps } from '@/components/Table/interface/index';

// 列表搜索项类型
export interface ListQueryData extends ReqPage {`
  list.forEach(item => {
    const { name, field, type } = item;
    if (type == '2' || type == '5') {
      state.v3typedefCode += `${field}:string | number | undefined;//${name}`
    } else {
      state.v3typedefCode += `${field}:string | undefined;//${name}`
    }
  })
  state.v3typedefCode += `}
// 列表state类型
export interface TableStateData {
  isView: boolean; //是否是查看
  activeId: string | number | undefined; //当前操作数据id`
  list.forEach(item => {
    const { name, field, type } = item;
    if (type == "2") {//select
      state.v3typedefCode += `${field}SelectList:any[],${name}下拉数据\n`
    }
    //部门选择,人员选择框,上传文件,上传图片
    if (type == "5" || type == "6" || type == "7" || type == "8") {
      state.v3typedefCode += `${field}List:any[],//${name}回显数据\n`
    }
    if (type == "5") {
      state.v3typedefCode += `initialOrgList:any[],//${name}回显部门\n`
    }
  });
  state.v3typedefCode += `queryParams: ListQueryData;
}

// 新增编辑state类型
export interface EditStateData {
  isView: boolean; //是否是查看
  visible: boolean; //弹窗显示
  title: string; //弹窗名称`
  list1.forEach(item => {
    const { name, field, type } = item;
    if (type == "2") {//select
      state.v3typedefCode += `${field}SelectList:any[],${name}下拉数据\n`
    }
    //部门选择,人员选择框,上传文件,上传图片
    if (type == "5" || type == "6" || type == "7" || type == "8") {
      state.v3typedefCode += `${field}List:any[],//${name}回显数据\n`
    }
    if (type == "5") {
      state.v3typedefCode += `initialOrgList:any[],//${name}回显部门\n`
    }
  });
  state.v3typedefCode += `form: {
   `
  list1.forEach(item => {
    const { name, field, type } = item;
    if (type == '2' || type == '5') {
      state.v3typedefCode += `${field}:string | number;//${name}`
    } else {
      state.v3typedefCode += `${field}:string;//${name}`
    }
  })
  state.v3typedefCode += `}; //表单
}
`
}
/**
 * v3生成代码结 ----------------
 */
/**
 * v2生成代码开 ----------------
 */
// 获取头 引入代码
const createv2topCode = () => {
  const { name, path, menuPath } = state.topInfo;
  const contextPath = "${pageContext.request.contextPath}"
  state.v2TableCode = `<%--${menuPath}--%>
  <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
  <script src="${contextPath}/jslib/vue-utils/vue-common-methods.js"><\/script>
  <script src="${contextPath}/js/api/${name}Api.js"><\/script>
  <script src="${contextPath}/js/${path}/${name}List.js"><\/script>\n`
}
// 获取搜索项html
const createv2SearchHeaderCode = () => {
  const { name } = state.topInfo;
  const list = getTypeList("search");
  state.v2TableCode += `<div id="${name}List" class="main_vue_container">
    <div class="vue_box_container">
        <common-header ${list.length > 3 ? 'show-more' : ''}>
            <el-form ref="${name}SearchForm" :model="queryParams" label-width="37.5%">
                <el-row>
                    <el-col :span="20">`;
  list.forEach(item => {
    const { name, field, type } = item;
    let singleItem = `\n\t\t\t<el-col :span="8">\n<el-form-item label="${name}" prop="${field}">\n`
    singleItem += getV2FormItemHtml(type, "queryParams", item);
    singleItem += `\n</el-form-item>\n</el-col>\n`
    state.v2TableCode += singleItem;
  })
  state.v2TableCode += `</el-col>
  <el-col style="display: flex;justify-content: flex-end;" :span="4">
    <el-button type="primary" icon="el-icon-search" @click="searchForm()">搜索</el-button>
    <el-button type="primary" icon="el-icon-refresh"  @click="resetSearchForm('${name}SearchForm')">重置</el-button>
</el-col>\n`;
  state.v2TableCode += `</el-row>
            </el-form>
        </common-header>
    </div>\n`
}
const getV2FormItemHtml = (type, subobjName, element) => {
  const { field, subType, formatterContent = 100 } = element;
  const selectname = `${field}SelectList`;
  const maxlength = formatterContent ? `maxlength=${formatterContent}` : ""
  switch (type) {
    case 1:
      return `<el-input ${maxlength} v-model="${subobjName}.${field}" placeholder="请输入"></el-input>`
    case 2:
      return `<el-select clearable v-model="${subobjName}.${field} " placeholder="请选择">
      <el-option v-for="item in ${selectname}" :key="item.id " :value="item.id ">{{item.name}}</el-option>
    </el-select>`
    case 3:
      return `<el-input rows="3" type="textarea" ${maxlength} v-model="${subobjName}.${field} "
      placeholder="请输入"></el-input>`
    case 4:
      return getDateHtml(subobjName, element, 2)
    case 5:
      if (subType == "单选") {
        return `<custom-tree-select
                  lazy
                  clearable
                  show-search
                  node-key="id"
                  v-model="${subobjName}.${field}"
                  :checked-list="${field}List"
                  :initial-org-list="initialOrgList"
                ></custom-tree-select>`
      } else {
        return `<custom-tree-select
                        multiple
                        check-child
                        clearable
                        show-search
                        node-key="id"
                        v-model="form.depids"
                        @removetag="removeTag"
                        v-if="initialOrgList.length>0"
                        :initial-org-list="initialOrgList"
                ></custom-tree-select>`
      }
    case 6:
      return `
    <person-select2
              type="1"
              ${subType == "单选" ? "single" : ""}
              @select="personSelect"
              :checked-person-list="${field}List"
      ></person-select2>`
    case 7:
      return `<uploader
                        limit="1"
                        exts="png,jpg,pdf,doc,docx,xlsx,xls,ppt,pptx,txt"
                        @success="handleFileSuccess"
                        @remove="handleFileDel"
                        :file-list="${subobjName}.${field}List">
                </uploader>`
    case 8:
      return `<uploader
                limit="1"
                file-type="image"
                exts="png,jpg,pdf,doc,docx,xlsx,xls,ppt,pptx,txt"
                @success="handleFileSuccess"
                @remove="handleFileDel"
                :file-list="${subobjName}.${field}List">
              </uploader>`

    case 9:
      return getRadioHtml(subobjName, element, 2)
    case 10:
      return getCheckBoxHtml(subobjName, element, 2)
  }
}
// v2列表生成
const createv2TableCode = () => {
  const list = getTypeList("table");
  const { name } = state.topInfo;
  state.v2TableCode += `<div class="vue_box_container">
        <common-table
                ref="${name}ListTable"
                :table-data="tableData"
                @load-table-data="getList"
                :table-header="tableHeader"
        >
            <div slot="toolbar">
                <el-button icon="el-icon-plus" type="primary" @click="handleAdd" v-permission="'${_getCodeName()}'">新增
                </el-button>
            </div>
            <template #cellset="{row,prop}">`
  list.forEach(item => {
    const { name, field, formatter } = item;
    if (formatter == '1') {
      state.v2TableCode += `\n<!-- ${name} -->
       <template v-if="prop == '${field}'">
           <p class="ellipsis_1" :title="row.${field}" v-if="row.${field}" style="text-align: center;">{{row.${field}}}</p>
          <p v-else>-</p>
      </template>\n`;
    }
  })
  state.v2TableCode += `</template>
        </common-table>
    </div>
  </div>`;
}
// v2列表js代码生成
const createv2TalejsDataCode = () => {
  const { name, menuPath } = state.topInfo;
  state.v2TablejsCode = `//${menuPath}
  new Vue({
    el: '#${name}List',
    data() {
        return {\n`
  state.v2TablejsCode += getV2data();//获取v2data一些额外变量，比如select的下拉项，人员选择部门选择回显等等
  state.v2TablejsCode += getV2queryParams();//获取v2queryParams搜索项
  state.v2TablejsCode += getV2tableHeader();//获取v2tableHeader
  state.v2TablejsCode += `tableData: { },//表格数据
      }
  },\n`
}
// 获取v2data一些额外变量，比如select的下拉项，人员选择部门选择回显等等
const getV2data = () => {
  const list = getTypeList("search");
  let html = ""
  list.forEach(item => {
    const { name, field, type, formatterContent } = item;
    if (type == "2") {//select
      html += `${field}SelectList:[//${name}下拉数据\n`
      const options = areaOptions(formatterContent)
      options.forEach(option => {
        html += `{id:${option.id},name:${option.name}},\n`
      })
      html += `],\n`
    }
    //部门选择,人员选择框,上传文件,上传图片
    if (type == "5" || type == "6" || type == "7" || type == "8") {
      html += `${field}List:[],//${name}回显数据\n`
    }
    if (type == "5") {
      html += `initialOrgList:[],//${name}回显部门\n`
    }
  });
  return html;
}
// 获取v2queryParams搜索项
const getV2queryParams = () => {
  const list = getTypeList("search");
  let html = `queryParams: {
                pageNum: 1,
                pageSize: 10,\n`;
  list.forEach(item => {
    const { name, field } = item;
    html += `${field}: undefined,//${name}\n`;
  });
  html += `},\n`
  return html;
}
// 获取v2tableHeader
const getV2tableHeader = () => {
  const list = getTypeList("table");
  let html = `tableHeader: [
    {prop: "index", label: '序号'},\n`;
  list.forEach(item => {
    const { name, field, formatter } = item;
    if (formatter == '1') {
      html += `{prop: "${field}", label: "${name}", formatter: (value, row) => {
                        if (value) {
                            return value;
                        } else {
                            return '-'
                        }
                    }},\n`;
    } else {
      html += `{prop: "${field}", label: "${name}"},\n`;
    }
  });
  html += `{
      prop: 'oper', label: '操作', width: '160px',align:"left",
      oper: [
          {
              name: '查看',
              permission: "${_getCodeName("view")}",
              onClick: this.handleView,
          },
          {
              name: '编辑',
              permission: "${_getCodeName("edit")}",
              onClick: this.handleEdit,
          },
          {
              name: '删除',
              type: 'danger',
              permission: "${_getCodeName("del")}",
              onClick: this.handleDelete
          },
      ]
  }`
  html += `],\n`
  return html;
}
// 获取v2列表js created
const createv2TalejsCreated = () => {
  const list = getTypeList("search");
  state.v2TablejsCode += `created() {\n`
  if (list.find(item => item.type == '5')) {
    state.v2TablejsCode += `new_common_api.getWholeOrgTreeOfLoginUser({}).then(res => {
      //所属部门返回选中数据
      this.initialOrgList = [{
        orgId: String(res.data.rows[0].id),
        text: res.data.rows[0].name
      }];
    }).catch(err => {
      console.log(err)
    });\n`
  }
  state.v2TablejsCode += `
        this.getList()
    },\n`
}
// 获取v2列表js methods
const createv2TalejsMethods = () => {
  state.v2TablejsCode += `methods: {\n`;
  state.v2TablejsCode += createv2TalejsFormatQueryParams();//获取v2列表js methods  formatQueryParams
  state.v2TablejsCode += createv2TalejsGetList();//获取v2列表js methods  getList
  state.v2TablejsCode += createv2TalejsOper();//获取v2列表js methods  操作项
  state.v2TablejsCode += createv2TalejsMethodsOther();//获取v2列表js methods
  state.v2TablejsCode += `},\n});`;
}
//获取v2列表js methods  formatQueryParams
const createv2TalejsFormatQueryParams = () => {
  let html = `//获取搜索数据
    formatQueryParams() {
       //获取搜索项
       let queryParams = JSON.parse(JSON.stringify(this.queryParams));`
  const list = getTypeList("search");
  list.forEach(item => {
    const { type, subType, field, name } = item;
    if (type == '4') {//日期选择
      if (subType == "daterange") {
        html += `//${name}
            if (queryParams.${field} && queryParams.${field}.length > 0 && queryParams.${field}[0]) {
                queryParams.starttime = queryParams.${field}[0] + " 00:00:00";
                queryParams.endtime = queryParams.${field}[1] + " 23:59:59";
            } else {
                queryParams.starttime = undefined;
                queryParams.endtime = undefined;
            }
            delete queryParams.${field};`
      }
    }
  })
  html += `return queryParams;
  },\n`
  return html;
}
//获取v2列表js methods  getList
const createv2TalejsGetList = () => {
  const { name } = state.topInfo;
  let html = `//获取列表
        getList(pageNum) {
            let queryParams = this.formatQueryParams();
            //获取分页信息进行搜索
            if (this.$refs.${name}ListTable) {
                //如果传过来指定值，就修改组件里的值，再次搜索
                if (pageNum) {
                    //这里必须得修改一下，不然再次搜索会影响分页。
                    this.$refs.${name}ListTable.pagination.pageNum = pageNum;
                }
                let pagination = this.$refs.${name}ListTable.pagination;
                queryParams.pageNum = pagination.pageNum;
                queryParams.pageSize = pagination.pageSize;
                this.$refs.${name}ListTable.canLoading = true;
            }

            ${humpTo(name)}_api.get${_getFirstUpperCase(name)}List(queryParams).then(res => {
                if (this.$refs.${name}ListTable) {
                    this.$refs.${name}ListTable.canLoading = false;
                }
                this.tableData = res.data;
            }).catch(err => {
              this.tableData = {rows:[{id: 1}],total:1};
                console.log(err);
            });
        },\n`

  return html;
}
//获取v2列表js methods  操作项
const createv2TalejsOper = () => {
  const { name } = state.topInfo;
  let html = `
    //新增
    handleAdd() {
     ${getOpenDialogHtml("新增")}
    },
    //查看
    handleView(row) {
      const id = row.id;
      ${getOpenDialogHtml("查看", '{id,pageType:"view"}')}
    },
     //编辑
    handleEdit(row) {
      const id = row.id;
      ${getOpenDialogHtml("编辑", '{id,pageType:"edit"}')}
    },
    //删除
    handleDelete(row) {
        const ids = row.id;
        let text = '是否确认删除该数据';
        let queryData = {
            id: ids
        }
        ELEMENT.Message.confirm(text).then(() => {
            ${humpTo(name)}_api.delete${_getFirstUpperCase(name)}(queryData).then(res => {
                ELEMENT.Message.success(res.msg || "删除成功");
                this.getList(1);
                $("#${name}List button[name='refresh']").click();
            }).catch(err => {
                console.log(err)
                ELEMENT.Message.error("删除失败");
            });
        }).catch(err => {
            console.log(err)
        });
    },\n`

  return html;
}
//获取v2列表js methods  其他方法
const createv2TalejsMethodsOther = () => {
  let html = `//搜索列表
        searchForm() {
            this.getList(1);//获取企业到期提醒表格列表
        },
        //重置搜索项
        resetSearchForm(searchForm) {
            this.$resetForm(searchForm);
        },\n`
  return html;
}
// 获取v2列表打开弹窗code
const getOpenDialogHtml = (title, data) => {
  const { name, path } = state.topInfo;
  let html = `
  $.myPlugin.modelDialog({
    context: contextPath + '/page/${path}/${name}Edit.jsp',
    ${data ? `data: ${data},` : ""}
    title:"${title}",
    width: '600px',
    height: "550px",
    offset: $("body").height() * 0.2 + 'px',
    resize: false,
    cancel: function (index, layero) {
      layer.closeAll('tips');
    }
  });
  `;
  return html;
}
// 获取v2弹窗头部引入代码
const createv2DialogtopCode = () => {
  const { name, path, menuPath } = state.topInfo;
  const contextPath = "${pageContext.request.contextPath}"
  state.v2DialogCode = `<%--${menuPath}-新增、编辑、查看--%>
  <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
  <script src="${contextPath}/jslib/vue-utils/vue-common-methods.js"><\/script>
  <script src="${contextPath}/js/api/${name}Api.js"><\/script>
  <script type="text/javascript">
    var ${name}EditId = <%=request.getParameter("id")%>;
    var pagetype = '<%=request.getParameter("pagetype")%>';//view:查看,edit:编辑,add：查看
<\/script>
  <script src="${contextPath}/js/${path}/${name}Edit.js"><\/script>\n`
}
// 获取v2弹窗外层html
const createv2DialogHtmlCode = () => {
  const { name } = state.topInfo;
  const list = getTypeList("form");
  // 新增编辑页面
  let html = `<div id="${name}Edit" class="main_vue_container dialog">
    <div class="${name}Edit_wrap dialog_wrap">
        <el-form v-if="pagetype != 'view'" ref="${name}EditForm" :model="form" :rules="rules" label-width="80px">\n`;
  let colCount = 1;
  list.forEach((item, index) => {
    const { name, field, type } = item,
      { isMultiseriate, multiseriateValue } = state,
      colnum = 24 / multiseriateValue;
    let singleItem = '';
    // 开启多行且一行大于1个表单
    if (isMultiseriate && multiseriateValue > 1) {
      if (colCount === 1) {
        singleItem += `<el-row>\n`
      }
      singleItem += `<el-col :span="${colnum}">\n`
    }
    singleItem += `<el-form-item label="${name}" prop="${field}">\n`
    singleItem += getV2FormItemHtml(type, "form", item);
    singleItem += `\n</el-form-item>\n`
    if (isMultiseriate && multiseriateValue > 1) {
      singleItem += `</el-col>\n`;
      if (colCount >= multiseriateValue || index == list.length - 1) {
        colCount = 1;
        singleItem += `</el-row>\n`
      } else {
        colCount++;
      }
    }
    html += singleItem;
  })
  html += `</el-form>
  ${getV2DialogviewCode()}
    </div>\n`;
  // 按钮
  html += `<div class="btn_bottom_wrap">
        <%-- 新增编辑时候显示的保存--%>
        <submit-button v-if="pagetype != 'view'" @response="response" formref="${name}EditForm"
                       :api="api">保存</submit-button>
        <el-button :type="pagetype == 'view'?'primary':''" @click="closeDialog()">{{pagetype == 'view'?'关闭':'取消'}}</el-button>
    </div>
    </div>`
  state.v2DialogCode += html;
}

// 获取v2弹窗查看代码
const getV2DialogviewCode = () => {
  const { name } = state.topInfo;
  const list = getTypeList("form");

  // 查看页面
  let html = `<el-form v-else ref="${name}View" :model="form" label-width="80px">\n`
  let colCount = 1;
  list.forEach((item, index) => {
    const { name, field, type } = item,
      { isMultiseriate, multiseriateValue } = state,
      colnum = 24 / multiseriateValue;
    // 开启多行且一行大于1个表单
    if (isMultiseriate && multiseriateValue > 1) {
      if (colCount === 1) {
        html += `<el-row>\n`
      }
      html += `<el-col :span="${colnum}">\n`
    }
    if (type == '5' || type == '6') {
      html += `<el-form-item label="${name}：">
        <p class="view_text">{{checkValidVal(form.${field}Name)}}</p>
    </el-form-item>\n`
    } else if (type == '7') {
      html += `<el-form-item label="${name}：" prop="${field}">
        <uploader
              isView
              :file-list="${field}List">
        </uploader>
      </el-form-item>\n`;
    } else if (type == '8') {
      html += `<el-form-item label="${name}：" prop="${field}">
        <uploader
              isView
              file-type="image"
              :file-list="${field}List">
        </uploader>
      </el-form-item>\n`;
    } else {
      html += `<el-form-item label="${name}：" prop="${field}">
        <p class="view_text">{{checkValidVal(form.${field})}}</p>
    </el-form-item>\n`;
    }
    if (isMultiseriate && multiseriateValue > 1) {
      html += `</el-col>\n`;
      if (colCount >= multiseriateValue || index == list.length - 1) {
        colCount = 1;
        html += `</el-row>\n`
      } else {
        colCount++;
      }
    }
  })
  html += `</el-form>\n`;

  return html;
}
// 获取v2弹窗js代码
const createv2DialogJsCode = () => {
  const { name, menuPath } = state.topInfo;
  // const list = getTypeList("form");
  state.v2DialogjsCode = `//${menuPath}-新增、编辑、查看
  new Vue({
    el: "#${name}Edit",
    ${getV2DialogJsDataCode()}
    ${getv2DialogjsCreated()}
    ${getv2DialogjsMethods()}
    });`
}
// 获取v2弹窗js data代码
const getV2DialogJsDataCode = () => {
  const { name } = state.topInfo;
  const list = getTypeList("form");
  const list1 = getTypeList("form,required");
  let html = ` data() {
        return {
            id: ${name}EditId,
            pagetype:pagetype,
            form: {
              id: undefined, //id\n`;
  list.forEach(item => {
    const { name, field } = item;
    html += `${field}:undefined,//${name}\n`;
  })
  html += ` },\n`;
  if (list1.length > 0) {
    html += `rules: {\n`;
    list1.forEach(item => {
      const { name, field, type } = item;
      const blurArr = ["1", "3"];
      if (blurArr.includes(type)) {
        html += `${field}:[
          {required: true, message: "请输入${name}", trigger: "blur"},
      ],\n`;
      } else {
        html += `${field}:[
          {required: true, message: "请选择${name}", trigger: "change"},
      ],\n`;
      }
    });
    html += `},\n`;
  }

  // 额外需要赋值的回显数据
  list.forEach(item => {
    const { name, field, type, formatterContent } = item;
    if (type == "2") {//select
      html += `${field}SelectList:[//${name}下拉数据\n`
      const options = areaOptions(formatterContent)
      options.forEach(option => {
        html += `{id:${option.id},name:${option.name}},\n`
      })
      html += `],\n`
    }
    //部门选择,人员选择框,上传文件,上传图片
    if (type == "5" || type == "6" || type == "7" || type == "8") {
      html += `${field}List:[],//${name}回显数据\n`
    }
    if (type == "5") {
      html += `initialOrgList:[],//${name}回显部门\n`
    }
  });
  html += `}
},\n`;
  return html;
}
// 获取v2弹窗js created
const getv2DialogjsCreated = () => {
  const list = getTypeList("form");
  let html = `created() {`
  if (list.find(item => item.type == '')) {
    html += `new_common_api.getWholeOrgTreeOfLoginUser({}).then(res => {
      //所属部门返回选中数据
      this.initialOrgList = [{
        orgId: String(res.data.rows[0].id),
        text: res.data.rows[0].name
      }];
    }).catch(err => {
      console.log(err)
    });\n`
  }
  html += `
       if (this.id) {
          this.getInfo();
      }
    },\n`
  return html;
}
// 获取v2弹窗js methods
const getv2DialogjsMethods = () => {
  const { name } = state.topInfo;
  let html = `methods: {
    //查询单条数据
        getInfo() {
            ${humpTo(name)}_api
                .get${_getFirstUpperCase(name)}Info({id: this.id})
                .then((res) => {
                    this.form = this.formatViewForm(res.data);
                })
                .catch((err) => {
                    ELEMENT.Message.error(err.msg || "获取数据失败");
                });
        },
        ${getv2DialogjsFormatViewForm()}
        ${getv2DialogjsApiResponse()}
        ${getv2DialogjsOther()}
        },`;
  return html;
}
// 获取v2弹窗js methods formatViewForm
const getv2DialogjsFormatViewForm = () => {
  const list = getTypeList("form");
  let html = `formatViewForm(data){`;
  // 声明变量
  html += `\nconst {`;
  list.forEach(item => {
    const { field, type } = item;
    if (type == '6') {
      html += `${field}, ${field}Names, userModels,`
    }
    if (type == '5') {
      html += `${field}, ${field}Names,`
    }
    if (type == '7' || type == '8') {
      html += `fileModels`
    }
  })
  html += `} = data;`;
  html += `let newForm = JSON.parse(JSON.stringify(data));
            newForm = this.$assign(this.form,newForm);`
  list.forEach(item => {
    const { name, field, type } = item;
    if (type == '6') {
      html += `//${name}选择
            //可能方法一
            if(${field} && ${field}Names){
                this.${field}List = [{id:${field},name:${field}Names}]
            }
            //可能方法二
            if(userModels?.length>0){
                this.${field}List = userModels.map(person=>{
                    const {${field},${field}Names} = person;
                    return {name:${field}Names,id:${field}}
                })
            }\n`;
    }
    if (type == '5') {
      html += `//部门选择
            newForm.${field} = String(${field});
            if(${field} && ${field}Names){
                this.${field}List = [{orgId:String(${field}),text:${field}Names}]
            }\n`;
    }
    if (type == '7' || type == '8') {
      const filename = ' `${ filetitle }.${ suffix } `';
      html += `//上传文件
            if(fileModels?.length>0){
                this.fileList = fileModels.map(item => {
                    let {filetitle, suffix, id} = item;
                    let obj = {
                        id,
                        name: ${filename}
                    }
                    return obj;
                })
            }
            return newForm;
        },\n`
    }
  })
  return html;
}
// 获取v2弹窗js methods api response formatSubmitForm
const getv2DialogjsApiResponse = () => {
  const { name } = state.topInfo;
  let html = `formatSubmitForm(){
            const newData = JSON.parse(JSON.stringify(this.form));
            return newData;
        },
        api() {
            const form = this.formatSubmitForm(this.form);
            if (this.id) {
                return ${humpTo(name)}_api.edit${_getFirstUpperCase(name)}(form);
            } else {
                return ${humpTo(name)}_api.add${_getFirstUpperCase(name)}(form);
            }
        },
        response(res) {
            if (res.success) {
                ELEMENT.Message.success(res.msg);
                $("#${name}List button[name='refresh']").click();
                this.closeDialog();
            } else {
                ELEMENT.Message.error(res.msg);
            }
        },`;
  return html;
}
// 获取v2弹窗js methods
const getv2DialogjsOther = () => {
  const list = getTypeList("form");
  const { name } = state.topInfo;
  let html = '';
  if (list.find(item => item.type == '6')) {
    html += `personSelect(data) {
          this.form.userIds = data.map(person=>person.id).join(",");
          this.checkedList = data;
      },\n`;
  }
  if (list.find(item => (item.type == '7' || item.type == '8'))) {
    html += `//附件上传成功
        handleFileSuccess(response, file, fileList) {
          const newfile = this.$getUploadFile(file)
          this.filesList.push(newfile);
          this.form.files = this.filesList.map(item => item.id).join(",")
        },
        //删除文件
        handleFileDel(file, fileList) {
          this.filesList = fileList;
          this.form.files = this.filesList.map(item => item.id).join(",")
          console.log(this.filesList, this.form.files)
        },\n `
  }
  html += `//检查有效值
		checkValidVal(val){
			if(val || val=='0'){
				return val;
			}
			return "-"
		},
  // 关闭弹窗
        closeDialog() {
            $("#${name}Edit").parents(".layui-layer-page").find(".layui-layer-close").click();
        }`
  return html;
}
// 生成v2api代码
const createV2ApiCode = () => {
  const { name, menuPath } = state.topInfo;
  state.v2ApijsCode = `
  var request = vue_common_utils.request;
  //${menuPath}
  var ${humpTo(name)
    }_api = {
  //列表
  get${_getFirstUpperCase(name)}List: function (params) {
    return request({
      url: "/${name}/get${_getFirstUpperCase(name)}List.do",
      data: params,
    })
  },
    //查询详情
    get${_getFirstUpperCase(name)}Info: function (params) {
  return request({
    url: "/${name}/get${_getFirstUpperCase(name)}Info.do",
    data: params,
  })
},
    // 新增
    add${_getFirstUpperCase(name)}: function (params) {
  return request({
    url: "/${name}/add${_getFirstUpperCase(name)}.do",
    data: params,
    method: "post"
  })
},
    // 编辑
    edit${_getFirstUpperCase(name)}: function (params) {
  return request({
    url: "/${name}/edit${_getFirstUpperCase(name)}.do",
    data: params,
    method: "post"
  })
},
    // 删除
    delete${_getFirstUpperCase(name)}: function (params) {
  return request({
    url: "/${name}/delete${_getFirstUpperCase(name)}.do",
    data: params,
    method: "post"
  })
},
}
`
}
/**
 * v2生成代码结 ----------------
 */
// 获取日 对应html
const getDateHtml = (subobjName, element, type) => {
  const { field, subType } = element
  let variate = `state.${subobjName}.${field}`;
  type === 2 && (variate = `${subobjName}.${field}`);
  switch (subType) {
    case "year":
      return `<el-date-picker value-format="YYYY" v-model="${variate}" type = "year"></el-date-picker> `
    case "date":
      return `<el-date-picker v-model="${variate}" type = "date" value-format="YYYY-MM-DD" placeholder = "请选择" ></el-date-picker> `
    case "datetime":
      return `<el-date-picker placeholder= "请选择" v-model="${variate}" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker> `
    case "daterange":
      return `<el-date-picker value-format="YYYY-MM-DD" v-model="${variate}" type="daterange" range-separator="~" start-placeholder="开始时间" end-placeholder="结束时间" ></el-date-picker> `
    case "datetimerange":
      return `< el-date-picker value-format="YYYY-MM-DD HH:mm:ss"
v-model="${variate}" type="datetimerange" range-separator="~" start-placeholder="开始时间"
end-placeholder="结束时间" ></el-date-picker> `
  }

}
// 获取单选html
const getRadioHtml = (subobjName, element, type) => {
  const { field, formatterContent } = element
  let variate = `state.${subobjName}.${field}`;
  type === 2 && (variate = `${subobjName}.${field}`);

  let html = `<el-radio-group v-model="${variate}">`;
  const options = areaOptions(formatterContent)
  console.log(options)
  options.forEach(option => {
    html += `<el-radio :label=${option.id}>${option.name}</el-radio>`;
  })
  html += `</el-radio-group>`;
  return html;
}
// 获取复选html
const getCheckBoxHtml = (subobjName, element, type) => {
  const { field, formatterContent } = element;
  let variate = `state.${subobjName}.${field}`;
  type === 2 && (variate = `${subobjName}.${field}`);

  let html = `<el-checkbox-group v-model="${variate}">`;
  const options = areaOptions(formatterContent)
  options.forEach(option => {
    html += `<el-checkbox label="${option.name}" value="${option.id}" ></el-checkbox>`;
  })
  html += `</el-checkbox-group> `;
  return html;
}
// 获取textarea中的数据
const areaOptions = (content) => {
  if (!content) {
    return []
  }
  const list = content.split("\n")
  return list.map(item => {
    const contentitems = item.split(":")
    console.log(contentitems)
    return { id: contentitems[0], name: contentitems[1] }
  })
}
// 当前数据存到localStorage
const setlocalStorage = () => {
  const { name, menuPath, path } = state.topInfo;
  const list = state.tablePropsList;
  const obj = { name, menuPath, path, list }
  let automatic = window.localStorage.getItem("automatic")
  automatic = (automatic && JSON.parse(automatic)) || {};
  automatic[name] = obj;
  window.localStorage.setItem("automatic", JSON.stringify(automatic));

  getHistoryList();// 获取历史列表
}
// 获取历史记录
const getHistoryList = () => {
  let automatic = window.localStorage.getItem("automatic")
  if (automatic) {
    automatic = JSON.parse(automatic);
    state.historySesstion = automatic;
    state.historySelectList = Object.keys(automatic).map(key => {
      return { name: key }
    })
  }
}
function historyChange(val) {
  const info = state.historySesstion[val]
  state.topInfo.name = info.name;
  state.topInfo.menuPath = info.menuPath;
  state.topInfo.path = info.path;
  state.tablePropsList = info.list || []
}
//
const moveChange = (params) => {
  console.log('params ==============>>>', params);
  console.log(state.tablePropsList)
}
// 获取code
const _getCodeName = (type = 'add') => {
  const suffix = type.toUpperCase()
  const code = `${humpTo(state.topInfo.name).toUpperCase()}_${suffix}`
  return code;
}
// 首字母大写
const _getFirstUpperCase = (word) => {
  return word.replace(/( |^)[a-z]/g, (L) => L.toUpperCase())
}
const _turnToPinyin = (queryString) => {
  const pyInput = pinyin(queryString, { toneType: 'none', type: 'array' }).join('');
  return pyInput;
}
</script>
<style>
h2 {
  text-align: left;
  padding: 10px 0 20px;
}

.button_wrap {
  text-align: left;
  padding-top: 20px;
}

.el-select {
  width: 100% !important;
}

.border {
  h4 {
    margin: 0;
  }

  .el-col {
    border-top: 1px solid #dddddd;
    border-left: 1px solid #dddddd;
    padding: 10px;
  }

  &.el-row {
    &:last-child {
      border-bottom: 1px solid #dddddd;
    }

    .el-col:last-child {
      border-right: 1px solid #dddddd;
    }
  }
}
</style>